package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.TextView;

public class BackWork3 extends Activity {
	TextView tv;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_backwork);
		tv = (TextView) findViewById(R.id.ch19_backwork_tv);
	}

	public void mOnClick(View v) {
		int start = 0, end = 100;
		int result;
		
		WaitDlg dlg = new WaitDlg(this, "WaitTest", "Now Calculating");
		dlg.start();
		
		result = Accumulate(start, end);
		tv.setText("" + result);
		
		WaitDlg.stop(dlg);
		

	}
	
	int Accumulate(int start, int end){
		int sum = 0;
		for(int i=start; i<=end; i++){
			sum+=i;
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return sum;
	}

}

class WaitDlg extends Thread {
	Context mContext;
	String mTitle;
	String mMsg;
	ProgressDialog mProgress;
	Looper mLoop;

	public WaitDlg(Context mContext, String mTitle, String mMsg) {
		super();
		this.mContext = mContext;
		this.mTitle = mTitle;
		this.mMsg = mMsg;

		setDaemon(true);
	}

	public void run() {
		Looper.prepare();
		mProgress = new ProgressDialog(mContext);
		mProgress.setTitle(mTitle);
		mProgress.setMessage(mMsg);
		mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgress.setCancelable(false);
		mProgress.show();

		mLoop = Looper.myLooper();
		Looper.loop();
	}

	static void stop(WaitDlg dlg) {
		dlg.mProgress.dismiss();
		
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		dlg.mLoop.quit();		
	}
}
